package com.fare.taluo.auth.dao;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;

import com.fare.taluo.auth.dao.base.BaseEntity;


@SuppressWarnings({ "unchecked", "rawtypes" })
public class BaseHibernateDao  {
	
	private SessionFactory sessionFactory;
	
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public BaseHibernateDao() {

	}

	/**
	 * 获取一个对象
	 * 
	 * @param <T>
	 * @param entityClass
	 *            对象类
	 * @param ids
	 * @return
	 */
	public <T extends BaseEntity> T findOneEntity(Class<T> entityClass, Long ids)
			throws Exception {
	//	return (T) getHibernateTemplate().get(entityClass, ids);
		return (T) sessionFactory.getCurrentSession().get(entityClass, ids);
	}

	/**
	 * 获取一个对象
	 * 
	 * @param <T>
	 * @param entityClass
	 *            对象类
	 * @param filterString
	 *            过滤HQL
	 * @return
	 * @throws Exception
	 */
	public <T extends BaseEntity> T findOneEntity(Class<T> entityClass,
			String filterString) throws Exception {
		Query query = sessionFactory.getCurrentSession().createQuery(
				"from " + entityClass.getName() + filterString);
		return (T) query.uniqueResult();
	}

	/**
	 * 获取多个对象
	 * 
	 * @param <T>
	 * @param entityClass
	 *            对象类
	 * @param filterString
	 *            过滤HQL
	 * @return
	 * @throws Exception
	 */
	public <T extends BaseEntity> List<T> findManyEntity(Class<T> entityClass,
			String filterString) throws Exception {
		Query query = sessionFactory.getCurrentSession().createQuery(
				"from " + entityClass.getName() + filterString);
		List<T> list = query.list();
		return list;
	}

	/**
	 * 获取多个对象
	 * @param <T>
	 * 
	 * @param <T>
	 * @param entityClass
	 *            对象类
	 * @param filterString
	 *            过滤HQL
	 * @return
	 * @throws Exception
	 */
	public <T> List<T> findEntities(Class<T> entityClass, String filterString)
			throws Exception {
		Query query = sessionFactory.getCurrentSession().createQuery(
				"from " + entityClass.getName() + filterString);
		List<T> list = query.list();
		return list;
	}

	/**
	 * 获取多个对象
	 * 
	 * @param <T>
	 * @param entityClass
	 *            对象类
	 * @param filterString
	 *            过滤HQL
	 * @param orderByString
	 *            排序
	 * @return
	 * @throws Exception
	 */
	public <T extends BaseEntity> List<T> findManyEntityByOrder(
			Class<T> entityClass, String filterString, String orderByString)
			throws Exception {
		Query query = sessionFactory.getCurrentSession().createQuery(
				"from " + entityClass.getName() + filterString + orderByString);
		List<T> list = query.list();
		return list;
	}

	/**
	 * 分页获取多个对象
	 * 
	 * @param entityClass
	 *            对象类
	 * @param filterString
	 *            过滤HQL
	 * @param queryResult
	 * @return
	 * @throws Exception
	 */
	public QueryResult findSplitPage(Class<? extends BaseEntity> entityClass,
			String filterString, QueryResult queryResult) throws Exception {
		Query queryCount = sessionFactory.getCurrentSession().createQuery(
				"select count(*) from " + entityClass.getName() + filterString);
		Long recordCount = (Long) queryCount.uniqueResult();

		Long currentPage = queryResult.getCurrentPage();// 当前页数
		Long maxResult = queryResult.getMaxResult();// 抓取数
		Long firstResult = (currentPage - 1l) == 0l ? 0l : (currentPage - 1l)
				* maxResult;// 开始处

		Query query = sessionFactory.getCurrentSession().createQuery(
				"from " + entityClass.getName() + filterString);
		query.setFirstResult(firstResult.intValue());
		query.setMaxResults(maxResult.intValue());

		queryResult.setRecordCount(recordCount);// 记录总数
		queryResult.setResultList(query.list());// 记录集

		queryResult.compute();// 计算

		return queryResult;
	}

	/**
	 * 分页获取多个对象
	 * 
	 * @param entityClass
	 *            对象类
	 * @param filterString
	 *            过滤HQL
	 * @param orderByString
	 *            排序
	 * @param queryResult
	 * @return
	 * @throws Exception
	 */
	public QueryResult findSplitPageByOrder(
			Class<? extends BaseEntity> entityClass, String filterString,
			String orderByString, QueryResult queryResult) throws Exception {

		Query queryCount = sessionFactory.getCurrentSession().createQuery(
				"select count(*) from " + entityClass.getName() + filterString
						+ orderByString);
		Long recordCount = (Long) queryCount.uniqueResult();

		Long currentPage = queryResult.getCurrentPage();// 当前页数
		Long maxResult = queryResult.getMaxResult();// 抓取数
		Long firstResult = (currentPage - 1l) * maxResult;// 开始处

		Query query = sessionFactory.getCurrentSession().createQuery(
				"from " + entityClass.getName() + filterString + orderByString);
		query.setFirstResult(firstResult.intValue());
		query.setMaxResults(maxResult.intValue());

		queryResult.setRecordCount(recordCount);// 记录总数
		queryResult.setResultList(query.list());// 记录集

		queryResult.compute();// 计算

		return queryResult;
	}

	/**
	 * 获取记录条数
	 * 
	 * @param entityClass
	 *            对象类
	 * @param filterString
	 *            过滤JPQL
	 * @return
	 * @throws Exception
	 */
	public Long findRecordCount(Class<? extends BaseEntity> entityClass,
			String filterString) throws Exception {
		Query query = sessionFactory.getCurrentSession().createQuery(
				"select count(*) from " + entityClass.getName() + filterString);
		Long recordCount = (Long) query.uniqueResult();
		return recordCount;
	}

	/**
	 * 根据SQL获取记录条数
	 * 
	 * @param SQL
	 * @return
	 * @throws Exception
	 */
	public Long findRecordCountBySql(String sql) throws Exception {
		Query query = sessionFactory.getCurrentSession().createSQLQuery(sql);
		BigDecimal count = (BigDecimal) query.uniqueResult();
		Long recordCount = count.longValue();
		return recordCount;
	}

	/**
	 * 根据SQL获取记录
	 * 
	 * @param SQL
	 * @param isBindMap是否封装为Map
	 * @return
	 * @throws Exception
	 */
	public List<?> findRecordBySql(String sql, boolean isBindMap)
			throws Exception {
		Query query = sessionFactory.getCurrentSession().createSQLQuery(sql);
		if (isBindMap)
			return query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
					.list();
		else
			return query.list();
	}

	/**
	 * 根据SQL获取记录
	 * 
	 * @param SQL
	 * @return
	 * @throws Exception
	 */
	public List<?> findRecordBySql(String sql) throws Exception {
		return findRecordBySql(sql, false);
	}

	/**
	 * 根据SQL获取一条记录
	 * 
	 * @param SQL
	 * @return
	 * @throws Exception
	 */

	public Map getRecordMapBySql(String sql) throws Exception {
		Query query = sessionFactory.getCurrentSession().createSQLQuery(sql);
		return (Map) query.setResultTransformer(
				Transformers.ALIAS_TO_ENTITY_MAP).uniqueResult();
	}

	/**
	 * 分页获取多个对象
	 * 
	 * @param SQL
	 * @param queryResult
	 * @return
	 * @throws Exception
	 */
	public QueryResult findSplitPageBySql(String sql, QueryResult queryResult)
			throws Exception {
		return findSplitPageBySql(sql, queryResult, false);
	}

	/**
	 * 分页获取多个对象
	 * 
	 * @param SQL
	 * @param isBindMap
	 * @param queryResult
	 * @return
	 * @throws Exception
	 */
	public QueryResult findSplitPageBySql(String sql, QueryResult queryResult,
			boolean isBindMap) throws Exception {
		Long recordCount = findRecordCountBySql("select count(*) from (" + sql
				+ ")");
		Long currentPage = queryResult.getCurrentPage();// 当前页数
		Long maxResult = queryResult.getMaxResult();// 抓取数
		Long firstResult = (currentPage - 1l) * maxResult;// 开始处

		Query query = sessionFactory.getCurrentSession().createSQLQuery(sql);
		query.setFirstResult(firstResult.intValue());
		query.setMaxResults(maxResult.intValue());

		queryResult.setRecordCount(recordCount);// 记录总数
		if (isBindMap)
			queryResult.setResultList(query.setResultTransformer(
					Transformers.ALIAS_TO_ENTITY_MAP).list());// Map记录集
		else
			queryResult.setResultList(query.list());// 记录集
		queryResult.compute();// 计算

		return queryResult;
	}

	/**
	 * 保存
	 * 
	 * @param entityClass
	 */
	public void saveOneEntity(BaseEntity entity) throws Exception {
		if (null == entity.getIds() || entity.getIds() == 0L) {
			sessionFactory.getCurrentSession().save(entity);
		}
	}

	/**
	 * 保存
	 * 
	 * @param entityClass
	 */
	public void dfSaveOneEntity(BaseEntity entity) throws Exception {
		if (null == entity.getIds() || entity.getIds() == 0L) {
			sessionFactory.getCurrentSession().save(entity);
			sessionFactory.getCurrentSession().flush();
		}
	}

	/**
	 * 更新
	 * 
	 * @param entityClass
	 * @param user
	 */
	public void updateOneEntity(BaseEntity entity) throws Exception {
		if (null != entity.getIds() && entity.getIds() != 0L) {
			sessionFactory.getCurrentSession().clear();
			sessionFactory.getCurrentSession().update(entity);
		}
	}

	/**
	 * 更新
	 * 
	 * @param entityClass
	 * @param user
	 */
	public void dfUpdateOneEntity(BaseEntity entity) throws Exception {
		if (null != entity.getIds() && entity.getIds() != 0L) {
			sessionFactory.getCurrentSession().update(entity);
		}
	}

	/** 清除session */
	public void clearSession() {
		sessionFactory.getCurrentSession().clear();
	}

	/**
	 * 保存或则更新
	 * 
	 * @param entity
	 */
	public void saveOrUpdate(BaseEntity entity) throws Exception {
		if (null == entity.getIds() || entity.getIds() == 0L) {
			sessionFactory.getCurrentSession().save(entity);
		}
		if (null != entity.getIds() && entity.getIds() != 0L) {
//			sessionFactory.getCurrentSession().update(entity);
			sessionFactory.getCurrentSession().merge(entity);//解决Hibernate持久化问题
		}
	}

	/**
	 * 删除
	 * 
	 * @param entityClass
	 * @param user
	 */
	public void deleteOneEntity(BaseEntity entity) throws Exception {
		if (entity != null && null != entity.getIds() && entity.getIds() != 0L) {
			sessionFactory.getCurrentSession().delete(entity);
		}
	}

	/**
	 * 执行一段HQL
	 * 
	 * @param HQL
	 * @return
	 */
	public int excuteHQL(String HQL) throws Exception {
		int processResult = 0;
		if (null != HQL && !HQL.trim().equals("")) {
			processResult = sessionFactory.getCurrentSession().createQuery(HQL).executeUpdate();
		}
		return processResult;
	}

	/**
	 * 执行一段SQL
	 * 
	 * @param SQL
	 * @return
	 */
	public int excuteSQL(String SQL) throws Exception {
		int processResult = 0;
		if (null != SQL && !SQL.trim().equals("")) {
			processResult = sessionFactory.getCurrentSession().createSQLQuery(SQL)
					.executeUpdate();
		}
		return processResult;
	}
}
